package com.gitee.maskit.web;

import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author z0228
 */

public enum WebHolder {
    AGENT,
    DOMAIN,
    PORT(80),
    LOCALE(Locale.getDefault()),
    SEO,
    REQUEST,
    RESPONSE;

    private static final ThreadLocal<Map<WebHolder, Object>> MAP_THREAD_LOCAL =
        ThreadLocal.withInitial(ConcurrentHashMap::new);

    private final Object defaultValue;

    WebHolder() {
        defaultValue = null;
    }

    WebHolder(Object o) {
        defaultValue = o;
    }

    public boolean has() {
        return MAP_THREAD_LOCAL.get().containsKey(this);
    }

    @SuppressWarnings("unchecked")
    public <T> T get() {
        final Object r = MAP_THREAD_LOCAL.get().get(this);
        if (null != r) {
            return (T) r;
        }
        return (T) defaultValue;
    }

    @SuppressWarnings("unchecked")
    public <T> T set(Object object) {
        return (T) MAP_THREAD_LOCAL.get().put(this, object);
    }

    @SuppressWarnings("unchecked")
    public <T> T clear() {
        return (T) MAP_THREAD_LOCAL.get().remove(this);
    }

    public static void clearAll() {
        MAP_THREAD_LOCAL.get().clear();
    }

    public static String header(final String header) {
        if (REQUEST.has()) {
            return ((HttpServletRequest) REQUEST.get()).getHeader(header);
        }
        return null;
    }

    public static Enumeration<String> headers(final String header) {
        if (REQUEST.has()) {
            return ((HttpServletRequest) REQUEST.get()).getHeaders(header);
        }
        return Collections.emptyEnumeration();
    }

    public static String host() {
        String host = null;
        if (REQUEST.has()) {
            host = ((HttpServletRequest) REQUEST.get()).getHeader(HttpHeaders.HOST);
        }
        if (null != host) {
            return host;
        }
        return "";
    }
}
